package com.android.showRoomApp.adapter;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.android.showRoomApp.R;
import com.android.showRoomApp.entity.ScreenMaterial;
import com.android.showRoomApp.util.FileUtils;
import com.android.showRoomApp.util.SocketUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivityListViewAdapter extends BaseAdapter {

    private Context context;
    private List<List<ScreenMaterial>> data;

    public MainActivityListViewAdapter(Context context, List<List<ScreenMaterial>> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        final ViewHolder viewHolder;
        if (view == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(context);
            view = inflater.inflate(R.layout.view_mainact_listitem,null);

            viewHolder.horizontalScrollView = view.findViewById(R.id.mainAct_listItem_scrollView);
            viewHolder.horizontalScrollViewContainer = view.findViewById(R.id.mainAct_listItem_scrollView_container);
            viewHolder.screenNameTextView = view.findViewById(R.id.mainAct_listItem_screenName);
            viewHolder.screenStatusImageView = view.findViewById(R.id.mainAct_listItem_screenStatus);
            viewHolder.screenLoopSwitch = view.findViewById(R.id.mainAct_listItem_switchBtn);

            //监听switch
            viewHolder.screenLoopSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    final boolean state = b;
                    //发送socket命令
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            ScreenMaterial screenMaterial = data.get(i).get(0);
                            if (screenMaterial.isConnect()) {
                                String sendData = screenMaterial.getScreenNO() + ":0:loop:" + (state ? "on" : "off");
                                boolean result = SocketUtils.sentSocketData(screenMaterial.getLocalIP(), screenMaterial.getPort(), sendData);
                            }else {
                                //屏幕离线
                                viewHolder.screenLoopSwitch.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(context,"屏幕离线",Toast.LENGTH_SHORT).show();
                                        viewHolder.screenLoopSwitch.setChecked(false);
                                    }
                                });
                            }
                        }
                    }).start();
                }
            });

            //添加view
            for (int j = 0; j < data.get(i).size(); j++) {
                final ScreenMaterial screenMaterial = data.get(i).get(j);
                //获取根视图
                final View scrollItemView = inflater.inflate(R.layout.view_mainact_listitem_scrollitem,null);
                //获取元素
                final ImageView imageView = scrollItemView.findViewById(R.id.mainAct_listItem_scrollView_container_image);
                final int finalJ = j;
                scrollItemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //如果屏幕离线则不做任何处理
                        if (!screenMaterial.isConnect())
                            return;
                        //如果正在轮播则不做任何处理
                        if (viewHolder.screenLoopSwitch.isChecked()){
                            return;
                        }
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (SocketUtils.checkSocketConnect(screenMaterial.getLocalIP(),screenMaterial.getPort())){
                                    if (screenMaterial.getMaterialType().equals("video")){
                                        // 判断是否正在展示，如果正在展示则不show，如果没有在展示则发送
                                        if (!screenMaterial.isShow()){
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    String sendData = screenMaterial.getScreenNO()+":"+screenMaterial.getPlayOrder()+":"+screenMaterial.getMaterialType()+":show";
                                                    boolean result = SocketUtils.sentSocketData(screenMaterial.getLocalIP(),screenMaterial.getPort(),sendData);
                                                    //如果设置成功则将其他的素材关闭
                                                    if (result) {
                                                        for (int k = 0; k < data.get(i).size(); k++) {
                                                            data.get(i).get(k).setShow(false);
                                                        }
                                                        data.get(i).get(finalJ).setShow(true);
                                                    }
                                                    scrollItemView.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            MainActivityListViewAdapter.this.notifyDataSetChanged();
                                                        }
                                                    });
                                                }
                                            }).start();
                                        }
                                        scrollItemView.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                                builder.setNeutralButton("play", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        new Thread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                String sendData = screenMaterial.getScreenNO()+":"+screenMaterial.getPlayOrder()+":"+screenMaterial.getMaterialType()+":play";
                                                                boolean result = SocketUtils.sentSocketData(screenMaterial.getLocalIP(),screenMaterial.getPort(),sendData);
                                                                if (result){
                                                                    System.out.println("设置成功");
                                                                }else {
                                                                    System.out.println("设置失败");
                                                                }
                                                            }
                                                        }).start();                               }
                                                });
                                                builder.setNegativeButton("pause", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        new Thread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                String sendData = screenMaterial.getScreenNO()+":"+screenMaterial.getPlayOrder()+":"+screenMaterial.getMaterialType()+":pause";
                                                                boolean result = SocketUtils.sentSocketData(screenMaterial.getLocalIP(),screenMaterial.getPort(),sendData);
                                                                if (result){
                                                                    System.out.println("设置成功");
                                                                }else {
                                                                    System.out.println("设置失败");
                                                                }
                                                            }
                                                        }).start();
                                                                                    }
                                                });
                                                builder.setPositiveButton("stop", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        new Thread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                String sendData = screenMaterial.getScreenNO()+":"+screenMaterial.getPlayOrder()+":"+screenMaterial.getMaterialType()+":stop";
                                                                boolean result = SocketUtils.sentSocketData(screenMaterial.getLocalIP(),screenMaterial.getPort(),sendData);
                                                                if (result){
                                                                    System.out.println("设置成功");
                                                                }else {
                                                                    System.out.println("设置失败");
                                                                }
                                                            }
                                                        }).start();                                                   }
                                                });
                                                builder.show();
                                            }
                                        });
                                    }else {
                                        String sendData = screenMaterial.getScreenNO()+":"+screenMaterial.getPlayOrder()+":"+screenMaterial.getMaterialType()+":show";
                                        boolean result = SocketUtils.sentSocketData(screenMaterial.getLocalIP(),screenMaterial.getPort(),sendData);
                                        if (result){
                                            System.out.println("设置成功");
                                            //如果设置成功则将其他的素材关闭
                                            if (result) {
                                                for (int k = 0; k < data.get(i).size(); k++) {
                                                    data.get(i).get(k).setShow(false);
                                                }
                                                data.get(i).get(finalJ).setShow(true);
                                            }
                                            scrollItemView.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MainActivityListViewAdapter.this.notifyDataSetChanged();
                                                }
                                            });
                                        }else {
                                            System.out.println("设置失败");
                                        }
                                    }
                                }
                            }
                        }).start();
                    }
                });
                viewHolder.horizontalScrollViewContainer.addView(scrollItemView,j);

                // 加载素材，默认显示html
                if (screenMaterial.getMaterialType().equals("pic") && !screenMaterial.getFile().isEmpty()){

                    // 判断权限
                    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        continue;
                    }
                    if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        Toast.makeText(context,"权限请求失败，无法缓存图片",Toast.LENGTH_SHORT).show();
                        continue;
                    }

                    final String[] splits = screenMaterial.getFile().split("/");
                    String imageName = splits[splits.length-1];
                    String[] splits2 = imageName.split("\\.");
                    final String imageType = splits2[splits2.length-1];

                    // 判断资源是否是图片，不是图片则显示错误图片
                    if (!(imageType.equals("jpg") || imageType.equals("png"))){
                        imageView.setImageResource(R.drawable.no_error);
                        continue;
                    }

                    // 从本地获取图片
                    final String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+imageName;
                    if (FileUtils.fileIsExists(path)){
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        imageView.setImageBitmap(bitmap);
                        continue;
                    }

                    // 获取图片存入缓存
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(context.getResources().getString(R.string.app_ip)+screenMaterial.getFile())
                            .get()
                            .build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            //解析响应
                            if (response.code() != 200)
                                return;
                            InputStream inputStream = response.body().byteStream();
                            final Bitmap bitmap= BitmapFactory.decodeStream(inputStream);

                            // 保存到本地
                            File file=new File(path);
                            file.createNewFile();
                            //创建文件输出流对象用来向文件中写入数据
                            FileOutputStream out=new FileOutputStream(file);
                            //将bitmap存储为jpg\png格式的图片
                            switch (imageType){
                                case "jpg":
                                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
                                    break;
                                case "png":
                                    bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
                                    break;
                            }
                            bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
                            //刷新文件流
                            out.flush();
                            out.close();

                            // 展示图片
                            imageView.post(new Runnable() {
                                @Override
                                public void run() {
                                    imageView.setImageBitmap(bitmap);
                                }
                            });
                        }

                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Log.i("zjq",e.toString());
                        }
                    });

                }else if (screenMaterial.getMaterialType().equals("video")){
                    //视频展示图
                    imageView.setImageResource(R.drawable.no_video);
                }
            }

            viewHolder.horizontalScrollViewContainer.invalidate();

            view.setTag(viewHolder);
        } else {
          viewHolder = (ViewHolder) view.getTag();
        }

        //设置屏幕连线状态和title
        viewHolder.screenNameTextView.setText(data.get(i).get(0).getScreenNO()+"-"+data.get(i).get(0).getScreenName());
        if (data.get(i).get(0).isConnect()){
            viewHolder.screenStatusImageView.setImageResource(R.drawable.circle_open);//设置屏幕是否连线
        }else {
            viewHolder.screenStatusImageView.setImageResource(R.drawable.circle_close);//设置屏幕是否连线
        }

        //设置素材item和选中
        for (int j = 0; j < data.get(i).size(); j++) {
            ScreenMaterial screenMaterial = data.get(i).get(j);

            View scrollItemView = viewHolder.horizontalScrollViewContainer.getChildAt(j);
            TextView textView = scrollItemView.findViewById(R.id.mainAct_listItem_scrollView_container_text);
            ImageView isShowIcon = scrollItemView.findViewById(R.id.mainAct_listItem_scrollView_container_isShow);

            //设置素材名称
            textView.setText(screenMaterial.getMaterial());
            isShowIcon.setVisibility(screenMaterial.isShow()?View.VISIBLE:View.INVISIBLE);
        }


        return view;
    }




    class ViewHolder {
        private HorizontalScrollView horizontalScrollView;
        private LinearLayout horizontalScrollViewContainer;
        private ImageView screenStatusImageView;
        private TextView screenNameTextView;
        private Switch screenLoopSwitch;
    }
}
